package core2.ch01file.iostream;
import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;

public class UpdateFile {
	public static void main(String args[]) throws IOException {
		String fname = "Write1.txt"; // ���Ƶ��ļ���
		String childdir = "backup"; // ��Ŀ¼��
		new UpdateFile().update(fname, childdir);
	}

	public void update(String fname, String childdir) throws IOException {
		File f1, f2, child;
		f1 = new File(fname); // ��ǰĿ¼�д����ļ�����f1
		child = new File(childdir); // ��ǰĿ¼�д����ļ�����child
		if (f1.exists()) {
			if (!child.exists()) // child������ʱ������Ŀ¼
				child.mkdir();
			f2 = new File(child, fname); // ����Ŀ¼child�д����ļ�f2
			if (!f2.exists() || // f2������ʱ����ڵ����ڽ���ʱ
					f2.exists() && (f1.lastModified() > f2.lastModified()))
				copy(f1, f2); // ����
			getinfo(f1);
			getinfo(child);
		} else
			System.out.println(f1.getName() + " file not found!");
	}

	public void copy(File f1, File f2) throws IOException {
		// �����ļ�����������
		FileInputStream rf = new FileInputStream(f1);
		FileOutputStream wf = new FileOutputStream(f2);
		// �����ļ����������
		int count, n = 512;
		byte buffer[] = new byte[n];
		count = rf.read(buffer, 0, n); // ��ȡ������
		while (count != -1) {
			wf.write(buffer, 0, count); // д�������
			count = rf.read(buffer, 0, n);
		}
		System.out.println("CopyFile " + f2.getName() + " !");
		rf.close(); // �ر�������
		wf.close(); // �ر������
	}

	public static void getinfo(File f1) throws IOException {
		SimpleDateFormat sdf;
		sdf = new SimpleDateFormat("yyyy��MM��dd��hhʱmm��");
		if (f1.isFile())
			System.out.println("<FILE>\t" + f1.getAbsolutePath() + "\t"
					+ f1.length() + "\t"
					+ sdf.format(new Date(f1.lastModified())));
		else {
			System.out.println(" \t" + f1.getAbsolutePath());
			File[] files = f1.listFiles();
			for (int i = 0; i < files.length; i++)
				getinfo(files[i]);
		}
	}
}
